const defaults = {

}
class Axios{
	constructor(instanceConfig) {
		this.defaults = instanceConfig;
	}
	// configOrUrl:有可能是地址，也有可能是配置对象
	// config:当configOrUrl是地址，那么config即是配置对象
	//        当configOrUrl是对象，那么config是undefined
	// config:{
	// 			url:"http://zhangpeiyue.com:3000/scoreList"
	// 		}
	request(configOrUrl,config={}){
		if(typeof configOrUrl === "string"){
			config.url = configOrUrl;
		}else{
			config = configOrUrl;
		}
		// 合并
		config = {
			...this.defaults,
			...config
		}
		// 增加默认值get
		config.method = config.method ?? "get";
		if(config.baseURL && !config.url.startsWith("http://")){
			config.url = config.baseURL+config.url;
		}
		const dispatchRequest = function(config){
			return new Promise((resolve,reject)=>{
				const request = new XMLHttpRequest();
				request.responseType = "json";
				request.open(config.method,config.url);
				request.send();
				request.onload = function(){
					resolve({
						config,
						headers:request.getAllResponseHeaders(),
						request,
						status:request.status,
						statusText:request.statusText,
						data:request.response
					});
				}
			})
		}
		let promise = Promise.resolve(config);
		promise = promise.then(dispatchRequest.bind(this),undefined);
		return promise;
		
	}
}
function createInstance(defaultConfig){
	// 创建Axios实例
	const context = new Axios(defaultConfig);
	const instance = Axios.prototype.request.bind(context) ;
	for(let key in context){
		instance[key] = context[key]
	}
	return instance;
}
const axios = createInstance(defaults);
export default axios;